package com.example.demo.task;

import com.example.demo.comm.RedisCache;
import com.example.demo.comm.SpringContextUtils;
import com.example.demo.utils.MultiPartDownLoadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static com.example.demo.utils.MultiPartDownLoadUtils.SEMIH_TIME;

/**
 * 内部类用于实现下载
 */
public class DownLoadThreadTask implements Runnable {
    private Logger logger = LoggerFactory.getLogger(DownLoadThreadTask.class);

    /**
     * 线程ID
     */
    private String downloadId;

    private Integer number;
    /**
     * 下载起始位置
     */
    private long startIndex;
    /**
     * 下载结束位置
     */
    private long endIndex;

    private CountDownLatch latch;

    /**
     * 服务器请求路径
     */
    private String serverPath;
    /**
     * 本地路径
     */
    private String localPath;

    public DownLoadThreadTask(Integer number,String downloadId, long startIndex, long endIndex, CountDownLatch latch, String serverPath, String localPath) {
        this.downloadId = downloadId;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.latch = latch;
        this.serverPath = serverPath;
        this.localPath = localPath;
        this.number =number;
    }

    @Override
    public void run() {
        try {
            logger.info("下载id:{}，序号：{}正在下载...",downloadId,number);
            URL url = new URL(serverPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestMethod("GET");
            //请求服务器下载部分的文件的指定位置
            conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
            conn.setConnectTimeout(5000);
            int code = conn.getResponseCode();
            logger.info("下载id:{}，序号：{},请求返回code:{},正在下载...",downloadId,number,code);
            //返回资源
            InputStream is = conn.getInputStream();
            RandomAccessFile raf = new RandomAccessFile(localPath, "rwd");
            //随机写文件的时候从哪个位置开始写
            raf.seek(startIndex);//定位文件
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                raf.write(buffer, 0, len);
            }
            is.close();
            raf.close();
            logger.info("下载id" + downloadId + "下载完毕");
        } catch (Exception e) {
            //线程下载出错
            MultiPartDownLoadUtils.flag = 1;
            logger.error(e.getMessage(),e);
        } finally {
            //计数值减一
            latch.countDown();
            //后期改成redis
            RedisCache bean = SpringContextUtils.getBean(RedisCache.class);
            bean.setCacheObject(downloadId,latch.getCount(),SEMIH_TIME,TimeUnit.SECONDS);
        }
    }
}